import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv('cleaned_Spambase.csv')

# 划分特征和标签
X = data.iloc[:, :-1]  # 获取除最后一列之外的所有列作为特征X
y = data.iloc[:, -1]   # 获取最后一列作为标签y

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建朴素贝叶斯模型
nb_model = GaussianNB()

# 训练朴素贝叶斯模型
nb_model.fit(X_train, y_train)

# 使用朴素贝叶斯模型进行分类
y_pred_nb = nb_model.predict(X_test)

# 计算准确率
accuracy_nb = accuracy_score(y_test, y_pred_nb)
print("Accuracy (Naive Bayes): ", accuracy_nb)

# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred_nb)

# 绘制热力图
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title('Confusion Matrix (Naive Bayes)')

plt.show()
